//
//  APIManagerConfig.m
//  BaoZhangWang
//
//  Created by 叶越悦 on 2017/6/15.
//  Copyright © 2017年 yyy. All rights reserved.
//

#import "APIManagerConfig.h"

@implementation APIManagerConfig

- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    self = [self init];
    if (self) {
        self.debugMode = [aDecoder decodeBoolForKey:@"debugMode"];
        self.logEnabel = [aDecoder decodeBoolForKey:@"logEnabel"];
        self.logJSON = [aDecoder decodeBoolForKey:@"logJSON"];
        self.requestBaseUrl = [aDecoder decodeObjectForKey:@"requestBaseUrl"];
        self.debugRequestBaseUrl = [aDecoder decodeObjectForKey:@"debugRequestBaseUrl"];
    }
    return self;
}

- (void)encodeWithCoder:(NSCoder *)aCoder {
    [aCoder encodeBool:_debugMode forKey:@"debugMode"];
    [aCoder encodeBool:_logEnabel forKey:@"logEnabel"];
    [aCoder encodeBool:_logJSON forKey:@"logJSON"];
    [aCoder encodeObject:_requestBaseUrl forKey:@"requestBaseUrl"];
    [aCoder encodeObject:_debugRequestBaseUrl forKey:@"debugRequestBaseUrl"];
}

- (BOOL)archive {
    NSString *cacheFolder = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
    NSString *path = [cacheFolder stringByAppendingPathComponent:@"APIManagerConfig"];
    return [NSKeyedArchiver archiveRootObject:self toFile:path];
}

+ (instancetype)unArchiveObject {
    NSString *cacheFolder = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
    NSString *path = [cacheFolder stringByAppendingPathComponent:@"APIManagerConfig"];
    return [NSKeyedUnarchiver unarchiveObjectWithFile:path];
}

+ (instancetype)shareConfig {
    static APIManagerConfig *config__;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        config__ = [self unArchiveObject];
        if (!config__) {
            config__ = [APIManagerConfig new];
            config__.debugMode = YES;
            config__.logEnabel = YES;
            config__.logJSON = YES;
        }
        [config__ archive];
    });
    return config__;
}

- (BOOL)debugMode {
#if DEBUG
    return _debugMode;
#else
    return NO;
#endif
}

- (BOOL)logEnabel {
#if DEBUG
    return _logEnabel;
#else
    return NO;
#endif
}

- (NSString *)requestBaseUrl {
#if DEBUG
    if (self.debugMode && self.debugRequestBaseUrl) {
        return self.debugRequestBaseUrl;
    } else {
        return _requestBaseUrl;
    }
#else
    return _requestBaseUrl;
#endif
}

@end
